<?php
namespace App\Http\Controllers;

use App\Models\Album;
use App\Models\Region;
use App\Models\Travelnote;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Schema;

class AlbumController extends WxBaseController{
    protected $except=['index','show','search','zan'];
    //推荐位列表
    public function index(){
        $albums = Album::where('display', 1)->where('recommend',1)->limit(5)->get();
        editImageUrl($albums);
        return $this->apiReturn(true,'success',$albums);
    }
    //
    public function search($id,$order='created_at',$num=10){
        $albums = Album::where('area',$id)->orderBy($order,'desc')->simplePaginate($num);
        foreach ($albums as $album){
            if($album->recommend==1){
                $album->coverimage = config('domain').'/'.$album->coverimage;
            }
        }
        return $this->apiReturn(true,'success',$albums);
    }
    public function show($id){
        $album = Album::where('id',$id);
        //更新浏览量
        if(Schema::hasColumn('albums', 'watch')){
            $album->increment('watch');
        };
        $arr=$album->get();
        if($arr[0]->recommend==1){
            $arr[0]->coverimage = config('domain').'/'.$arr[0]->coverimage;
        }
        $num = Album::where('wxuser_id',$arr[0]->wxuser_id)->count();
        $note = Travelnote::where('wxuser_id',$arr[0]->wxuser_id)->count();
        $arr[0]->num=$num;
        $arr[0]->note=$note;
        return $this->apiReturn(true,'success',$arr[0]);
    }

    //写画册
    public function store(){
        $input = request();
        $areas = Region::all()->pluck('text','id');
        $area = 5;
        foreach ($areas as $k=>$val){
            if(strpos($input->address,$val)){
                $area=$k;
                break;
            }
        }
        $params =[
            'content'=>$input->con,
            'coverimage'=>$input->pic,
            'address'=>$input->address,
            'avatar'=>$this->auth()->avatarUrl,
            'nickname'=>$this->auth()->nickName,
            'wxuser_id'=>$this->auth()->id,
            'title'=>'用户上传',
            'area'=>$area,
            'created_at'=>time(),
            'updated_at'=>time()
        ];
        $id = Album::insertGetId($params);
        return $this->apiReturn(true,'success',Album::find($id));
    }
    //画册点赞
    public function zan(){
        $album_id=request()->album_id;
        //更新点赞
        $zan = Album::where('id',$album_id);
        $zan->increment('zan');
        return $this->apiReturn(true,'success',$zan->get(['zan']));
    }
}